// pages/allssembledetails/allssembledetails.js
var utils = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var start_time = ""; //开始时间 需要重新定义  2019-01-23
var end_time = ""; //结束时间 需要重新定义 2019-01-25
var now_time = '';
let len = "";
var datetime = "";

function getTimeStr(maxtime) {
    var result = '';
    if (maxtime == undefined) {
        maxtime = 0;
    }
    var second = parseInt(maxtime); // 秒
    var min = 0; // 分
    var hour = 0; // 小时
    if (second > 60) {
        min = parseInt(second / 60);
        second = parseInt(second % 60);
        if (min > 60) {
            hour = parseInt(min / 60);
            min = parseInt(min % 60);
        }
    }
    var result = "" + parseInt(second);
    if (min > 0) {
        result = "" + parseInt(min) + ":" + result;
    }
    if (hour > 0) {
        result = "" + parseInt(hour) + ":" + result;
    }
    return result;
}

function CountDown() {
    var result = '';
    now_time = Date.parse(new Date()) / 1000;
    // 活动未开始 

    if (parseInt(now_time) - parseInt(start_time) < 0) {
        result = "距开始还剩" + getTimeStr(parseInt(start_time) - parseInt(now_time));
        return result;
    } else if (parseInt(now_time) - parseInt(start_time) == 0) {
        return '活动开始';
    } else if (parseInt(now_time) - parseInt(end_time) < 0) {
        result = "距结束还剩" + getTimeStr(parseInt(end_time) - parseInt(now_time));
        return result;
    } else {
        clearInterval(timer);
        return '活动已结束';
    }
}
//时间数据长度        
function nowTime() {
    //时间函数     
    // console.log(a)      
    for (var i = 0; i < len; i++) {
        var intDiff = datetime[i].dat;
        //获取数据中的时间戳       
        // console.log(intDiff)       
        var day = 0,
            hour = 0,
            minute = 0,
            second = 0;
        if (intDiff > 0) {
            //转换时间         
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            if (hour <= 9) hour = '0' + hour;
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            datetime[i].dat--;
            var str = hour + ':' + minute + ':' + second
            //  console.log(str)        
        } else {
            var str = "已结束！";
            // clearInterval(timer1111);
        }

        datetime[i].difftime = "剩余" + str;
        // console.log(datetime[i])
        //在数据中添加difftime参数名，把时间放进去    
    }
    // console.log(datetime)

    return datetime

}
var timer1111 = '';
var timer = '';
Page({

    /**
     * 页面的初始数据
     */
    data: {
      isCoupn: false,
      isHtml: false,
        ishidden: true,
        coupon: "领劵",
      ishise: false
    },
    saveCanvas: function() {
        var that = this;
      var url = 'https://xinong.qidian2018.com/index.php?share_id=1&type=1&id=' + that.data.data.id + '&member_id=' + that.data.memberInfo.id;
        console.log(url);
        that.setData({
            qrcodeValue: url,
        }, function() {
            var canvas = that.selectComponent('#goods-share');
            canvas.saveImg();
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this;
        console.log("这个是分享获取的ID" + options.id);
        that.memberInfo();
        that.groupgoodsDetail(options.id);
        that.groupOther(options.id);
        that.commentslist(options.id);
        that.coupnlistTap(options.id);

    },
  //分享弹窗
  onshareTap: function (e) {
    var that=this;
    var url = 'https://xinong.qidian2018.com/index.php?share_id=1&type=1&id=' + that.data.data.id + '&member_id=' + that.data.memberInfo.id;;
    that.setData({
      qrcodeValue: url,
      ishise: true
    })
    console.log(this.data.qrcodeValue)
  },
  buttonOrderCalse: function (e) {
    this.setData({
      ishise: false
    })
  },
  //领取优惠券
  onCouponTap: function () {
    this.setData({
      isCoupn: true,
      isHtml: false,
    })
  },
  //领取优惠券  关闭
  onCouponClaseTap: function () {
    this.setData({
      isCoupn: false,
      isHtml: false,
    })
  },

  //参数
  onHtmlTap: function () {
    this.setData({
      isHtml: true,
      isCoupn: false
    })
  },
  //参数
  onHtmlClaseTap: function () {
    this.setData({
      isHtml: false,
      isCoupn: false
    })
  },
  //优惠卷使用
  onIndexTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    // 收取优惠券
    utils.http("/api/v1/coupon/get_coupon", {
      coupon_id: that.data.couponList[index].id
    }, function (res) {
      if (res.state == 1) {
        that.setData({
          isCoupn: false,
          coupon: that.data.couponList[index].money
        })
      } else {
        utils.message(res.datas)
      }
    })

  },
  //优惠券列表
  coupnlistTap: function (id) {
    var that = this;
    utils.showLoading();
    utils.http("/api/v1/goods/coupon_list", {
      goods_id: id
    }, function (res) {
      utils.hideLoading();
      that.setData({
        couponList: res.datas,
      });
    })
  },
    memberInfo: function() {
        var that = this;
        utils.http("/api/v1/member/index", {}, function(res) {
            that.setData({
                memberInfo: res.datas
            })
        });
    },
    groupgoodsDetail: function(id) {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/groupgoods/goods_detail", {
            id: id
        }, function(res) {
            utils.hideLoading();
            WxParse.wxParse('article', 'html', res.datas.content, that, 5);
			WxParse.wxParse('article1', 'html', res.datas.goods_info.goods_param, that, 5);
            start_time = res.datas.start_time; //开始时间 需要重新定义  2019-01-23
            end_time = res.datas.end_time;
            // 开始倒计时
            timer = setInterval(function() {
                that.setData({
                    lastName: CountDown().slice(0, 5),
                    lastTime: CountDown().slice(5, 16)
                });
            }, 1000);
            that.setData({
                data: res.datas,
            })
        })
    },
    //获取快要拼团成功的拼团的列表
    groupOther: function(id) {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/groupgoods/group_other", {
            group_id: id
        }, function(res) {
            utils.hideLoading();
            var startTime = Date.parse(new Date()) / 1000;
            var pppTime = [];
            for (var i in res.datas) {
                var time = res.datas[i].last_time - startTime;
                pppTime.push({
                    dat: time
                })
            }
            len = pppTime.length;
            datetime = pppTime
            timer1111 = setInterval(function() {
                that.setData({
                    nowTime: nowTime()
                });
            }, 1000)
            that.setData({
                oter: res.datas,
            })
        })
    },
    //商品评价
    commentslist: function(id) {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/goods/comments_list", {
            be_id: id
        }, function(res) {
            utils.hideLoading();
            var commentsPost = []
            for (var i = 0; i < 2; i++) {
                commentsPost.push(res.datas.list[i])
            }
            that.setData({
                comments: commentsPost,
                commentsAll: res.datas.list
            })
        })
    },
    preventTouchMove() {},
    //跳转商品评价更多页面
    onEvaluateTap: function(e) {
        wx.navigateTo({
            url: '../commoditydetails/moreevaluatelist/moreevaluatelist',
        })
    },
    //立即购买
    buyNowTap: function(e) {
        var id = e.currentTarget.dataset.id;
        var goodsid = e.currentTarget.dataset.goodsid;
        var image = e.currentTarget.dataset.image;
        var name = e.currentTarget.dataset.name;
        var subtitle = e.currentTarget.dataset.subtitle;
        var price = e.currentTarget.dataset.price;
        var groupsn = e.currentTarget.dataset.groupsn;
        console.log(groupsn)
        var num = 1;
        wx.navigateTo({
            url: '../allConfirmoder/allConfirmoder?id=' + id + "&goodsid=" + goodsid + "&groupsn=" + groupsn + "&num=" + num + "&name=" + name + "&subtitle=" + subtitle + "&price=" + price + "&image=" + image
        })
    },
    //拼团规则
    onGuiZeTap: function(e) {
        var that = this;
        that.setData({
            ishidden: false
        })
    },
    //关闭拼团规则
    onColseGuiZeTap: function(e) {
        var that = this;
        that.setData({
            ishidden: true
        })
    },
    //单独购买
    buydanNowTap: function(e) {
        var that = this;
        var cartInfo = wx.getStorageSync('cartInfo') ? wx.getStorageSync('cartInfo') : []
        var spec_id = that.data.data.spec_id;
        var spec_num = 1;
        var specIdArr = [];
        cartInfo.forEach((value) => {
            specIdArr.push(value.spec_id);
        });
        //购物车存在该商品
        if (specIdArr.indexOf(spec_id) > -1) {
            console.log('购物车存在该商品', spec_id)
            for (var value in cartInfo) {
                if (cartInfo[value].spec_id == spec_id) {
                    cartInfo[value].number = cartInfo[value].number + spec_num
                    break;
                }
            }
            console.log('购物车存在该商品~~~', cartInfo)
        } else {
            cartInfo.unshift({
                spec_id,
                number: spec_num,
                selectStatus: false
            });
        }
        wx.setStorage({
            key: 'cartInfo',
            data: cartInfo,
            success: function() {
                var numberCount = 0;
                cartInfo.forEach((value) => {
                    numberCount = numberCount + value.number
                });
                wx.setStorageSync("number", numberCount);
                wx.setTabBarBadge({
                    index: 3,
                    text: String(numberCount),
                })
            }
        });
        wx.switchTab({
            url: '../cartshopp/cartshopp',
        })
    },
    onShareAppMessage: function() {
		return utils.share("", this.data.data.goods_info.name);
    },
})